package com.myproject.myblogserver.controller;

import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myproject.myblogserver.contant.CommonConstants;
import com.myproject.myblogserver.dto.PageResultDto;
import com.myproject.myblogserver.dto.user.UserInfoSimpleDto;
import com.myproject.myblogserver.entity.User;
import com.myproject.myblogserver.entity.UserFollow;
import com.myproject.myblogserver.service.IMyUserInfoService;
import com.myproject.myblogserver.service.IUserFollowService;
import com.myproject.myblogserver.service.IUserService;
import com.myproject.myblogserver.utils.JwtUtil;
import com.myproject.myblogserver.utils.TokenUtil;

import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;

/**
 * <p>
 * 用户关注表 前端控制器
 * </p>
 *
 * @author jiangweike
 * @since 2025-02-16
 */
@Controller
@RequestMapping("/userFollow")
public class UserFollowController {

    @Autowired
    private IUserFollowService userFollowService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IMyUserInfoService myUserInfoService;

    @PostMapping("/add/{id}")
    public ResponseEntity<?> add(@PathVariable Long id,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);
            var userFollow = new UserFollow();

            userFollow.setFollowerId(id);
            userFollow.setFollowingId(userId);
            userFollow.setIsDeleted(false);
            userFollowService.save(userFollow);

            return ResponseEntity.ok("关注成功!");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("关注失败！");
        }
    }

    @PostMapping("/delete/{id}")
    public ResponseEntity<?> delete(@PathVariable Long id,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);
            var userFollow = userFollowService.lambdaQuery()
                    .eq(UserFollow::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(UserFollow::getFollowerId, userId)
                    .eq(UserFollow::getFollowingId, id)
                    .select(UserFollow::getId)
                    .one();

            userFollow.setFollowerId(userId);
            userFollow.setFollowingId(id);
            userFollowService.updateById(userFollow);

            return ResponseEntity.ok("取关成功!");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("取关失败！");
        }
    }

    /**
     * 获取关注者列表
     * 
     * @param authHeader
     * @return
     */
    @PostMapping("/getFollowers/{pageIndex}")
    public ResponseEntity<?> getFollowers(@PathVariable Integer pageIndex,
            @RequestHeader("Authorization") String authHeader) {
        try {
            String refreshToken = TokenUtil.extractToken(authHeader);
            String userId = JwtUtil.getUserIdFromToken(refreshToken);

            var followerIds = userFollowService.lambdaQuery()
                    .eq(UserFollow::getFollowingId, Long.parseLong(userId))
                    .eq(UserFollow::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .select(UserFollow::getFollowerId)
                    .list()
                    .stream()
                    .map(UserFollow::getFollowerId)
                    .collect(Collectors.toList());

            var followerPage = userService.lambdaQuery()
                    .in(!followerIds.isEmpty(), User::getId, followerIds)
                    .eq(followerIds == null || followerIds.isEmpty(), User::getId, -1)
                    .eq(User::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .select(User::getId, User::getAvatar, User::getBio, User::getName)
                    .page(new Page<>(pageIndex, CommonConstants.DEFAULT_PAGE_SIZE));

            var pageResultDto = new PageResultDto<UserInfoSimpleDto>();
            pageResultDto.setTotalPages(followerPage.getPages());

            Map<Long, Long> followerCountMap = myUserInfoService.getFollowerCountMap(followerPage);

            // 构建DTO列表
            for (User follower : followerPage.getRecords()) {
                UserInfoSimpleDto dto = new UserInfoSimpleDto();
                dto.setId(follower.getId());
                dto.setAvatar(follower.getAvatar());
                dto.setBio(follower.getBio());
                dto.setName(follower.getName());
                dto.setFollowerCount(followerCountMap.getOrDefault(follower.getId(), 0L));
                pageResultDto.getContent().add(dto);
            }

            return ResponseEntity.ok(pageResultDto);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("获取粉丝列表失败");
        }
    }

    /**
     * 获取关注列表（当前用户关注的用户列表）
     * 
     * @param pageIndex  分页页码
     * @param authHeader 认证头
     * @return 分页的关注用户列表
     */
    @PostMapping("/getFollowings/{pageIndex}")
    public ResponseEntity<?> getFollowings(@PathVariable Integer pageIndex,
            @RequestHeader("Authorization") String authHeader) {
        try {
            String refreshToken = TokenUtil.extractToken(authHeader);
            String userId = JwtUtil.getUserIdFromToken(refreshToken);

            // 获取当前用户关注的用户ID列表（followingIds）
            var followingIds = userFollowService.lambdaQuery()
                    .eq(UserFollow::getFollowerId, Long.parseLong(userId))
                    .eq(UserFollow::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .select(UserFollow::getFollowingId)
                    .list()
                    .stream()
                    .map(UserFollow::getFollowingId)
                    .collect(Collectors.toList());

            // 分页查询关注的用户信息
            var followingPage = userService.lambdaQuery()
                    .in(!followingIds.isEmpty(), User::getId, followingIds)
                    .eq(followingIds.isEmpty(), User::getId, -1) // 简化空列表判断
                    .eq(User::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .select(User::getId, User::getAvatar, User::getBio, User::getName)
                    .page(new Page<>(pageIndex, CommonConstants.DEFAULT_PAGE_SIZE));

            var pageResultDto = new PageResultDto<UserInfoSimpleDto>();
            pageResultDto.setTotalPages(followingPage.getPages());

            Map<Long, Long> followerCountMap = myUserInfoService.getFollowerCountMap(followingPage);

            // 构建DTO列表
            for (User following : followingPage.getRecords()) {
                UserInfoSimpleDto dto = new UserInfoSimpleDto();
                dto.setId(following.getId());
                dto.setAvatar(following.getAvatar());
                dto.setBio(following.getBio());
                dto.setName(following.getName());
                dto.setFollowerCount(followerCountMap.getOrDefault(following.getId(), 0L));
                pageResultDto.getContent().add(dto);
            }

            return ResponseEntity.ok(pageResultDto);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("获取关注列表失败");
        }
    }
}
